from src.core import log
from src.db import dbm, dbs
from src.core.variables.info import sof
from src.schema.core import function_control_schema
from src.core.variables.status import SUCCESS_CODE_CUSTOMIZE, ERROR_CODE


def function_control(schema: function_control_schema):
    match schema.behavior:
        case "enable" | "disable":
            with dbm.get("sys_default") as db_session:
                from sqlalchemy.orm import scoped_session

                db_session: scoped_session
                db_result = (
                    db_session.query(dbs.sys_default.Function)
                    .filter(dbs.sys_default.Function.name == schema.name)
                    .first()
                )
                if db_result:
                    match schema.behavior:
                        case "enable":
                            db_result.status = "enable"
                        case "disable":
                            db_result.status = "disable"
                if dbm.commit(db_session):
                    sof.multi_node = True
                    return SUCCESS_CODE_CUSTOMIZE("操作成功！", 200)
                else:
                    db_session.rollback()
                    sof.multi_node = False
                    raise ERROR_CODE.SUBMISSION_FAILED()
        case _:
            log.WARNING(f"功能行为错误")
